<template>
  <!-- 班组选择（根据分包商和项目） -->
  <a-select
    v-bind="$attrs"
    v-on="$listeners"
    :placeholder="placeholder"
    :optionFilterProp="optionFilterProp"
    v-model="currentValue"
    allowClear
  >
    <a-icon v-if="fetching" style="color: #096dd9" slot="suffixIcon" type="loading" />
    <a-spin v-if="fetching" slot="notFoundContent" size="small" />
    <a-select-option v-for="i in list" :key="i.id" :value="i.id">{{ i.name }}</a-select-option>
  </a-select>
</template>
<script>
import { team } from '@/api/quality/quality'

export default {
  name: 'SelectTeam',
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Object],
    },
    // 搜索时需要联动的表单，
    form: {
      type: Object,
      default: () => ({}),
    },
    // 搜索时需要联动的表单名
    keyValue: {
      type: Array,
      default: () => ['projectId', 'subContractorId'],
    },
    // false:直属组织ID;true:组织ID及其下级组织
    isRoot: {
      type: Boolean,
      default: () => true,
    },
    // placeholder
    placeholder: {
      type: String,
      default: () => '请选择',
    },
    // 搜索时过滤对应的 option 属性，如设置为 children 表示对内嵌内容进行搜索,否则为value
    optionFilterProp: {
      type: String,
      default: () => 'children',
    },
    // 联动表单值改变时是否清空当前表单值
    isClear: {
      type: Boolean,
      default: () => true,
    },
    //如果是编辑，第一次不要重置绑定的值。。。。
    isEdit: {
      type: Boolean,
      default: () => false,
    },
  },
  data() {
    return {
      isCanClear: !this.isEdit, // 是否清除
      fetching: false,
      list: [],
    }
  },
  watch: {
    attr(val, old) {
      if (val[this.keyValue[0]] === old[this.keyValue[0]] && val[this.keyValue[1]] === old[this.keyValue[1]]) {
        return
      }
      // 清空表单
      if (this.isClear && !this.isEdit) {
        this.currentValue = void 0
        this.$emit('resetSelf') // 在搜索组件(SearchData)中重置自身的值
      }
      // 清空表单
      if (this.isEdit && this.isCanClear) {
        this.currentValue = void 0
        this.$emit('resetSelf') // 在搜索组件(SearchData)中重置自身的值
      } else {
        this.isCanClear = true
      }
      // 重置列表
      this.list = []
      val && this.getList()
    },
  },
  mounted() {
    // 初始化
    this.getList()
  },
  methods: {
    /**
     * 获取列表
     */
    getList() {
      if (!this.attr[this.keyValue[0]] || !this.attr[this.keyValue[1]]) {
        return
      }
      let params = {
        projectId: this.attr[this.keyValue[0]],
        subContractorId: this.attr[this.keyValue[1]],
      }
      this.fetching = true
      team
        .getList(params)
        .then((res) => {
          this.fetching = false
          this.list = res.data
          this.$emit('update:list', res.data)
        })
        .catch((res) => {
          this.fetching = false
        })
    },
    transKeyValue(_key){
      let attrValue
      const keys = _key.split('.')
      const findValueFromKeys = (data, key) => {
        if(data instanceof Object && keys.some(k => k === key)){
          return findValueFromKeys(data[key], keys[keys.findIndex(k => k === key) + 1])
        }
        return data
      }
      if(keys && !!keys.length){
        attrValue = findValueFromKeys(this.form, keys[0])
      }else{
        attrValue = this.form[keys[0]]
      }
      return attrValue
    }
  },
  computed: {
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        return this.value || void 0
      },
      set: function (value) {
        this.$emit('input', value)
      },
    },
    // 需要联动的表单值
    attr() {
      if(!(this.keyValue instanceof Array) && this.keyValue.length < 2){
        console.error('"keyValue" must defined a Array and the length exceed 2')
        return
      }
      return this.keyValue.reduce((total, key) => ({
        ...total,
        [key]: this.transKeyValue(key),
      }), {})
    },
  },
}
</script>
